﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;

namespace MammothMicro.SmtpGuardFilter
{
    public static class Tools
    {
        ///<summary>
        /// Clears any empty records from list
        ///</summary>
        ///<param name="list"></param>
        ///<returns></returns>
        public static List<string> ClearEmptyItems(List<string> list)
        {
            list.RemoveAll(p => p.Length == 0);
            return list;
        }

   
        /// <summary>
        /// Extracts Ip numbers from mail headers
        /// Optionally include found local IP numbers
        /// </summary>
        /// <param name="message"></param>
        /// <param name="removeLocalIp"></param>
        /// <returns></returns>
        public static IEnumerable<IPAddress> ExtractIp (MailMessage message, bool removeLocalIp = true)
        {
            var ips = new List<IPAddress>();
            foreach (string s  in message.Headers.Keys)
            {
                Debug.WriteLine(message.Headers[s.ToString()]);
                const string expr = @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";
          
                var matchCollection =Regex.Matches(message.Headers[s], expr);
                foreach (var match in matchCollection)
                {
                    ips.Add(IPAddress.Parse(match.ToString())); ;
                }
            }
            if(removeLocalIp)
            {
                ips.RemoveAll(p => p.ToString().StartsWith("192.168."));
                ips.RemoveAll(p => p.ToString().StartsWith("10."));
            }

            return ips;
        }

        /// <summary>
        /// Gets domain from email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static string GetDomainFromEmail(string email)
        {
            return email.Substring(email.IndexOf("@") + 1);
        }
        /// <summary>
        /// Available filters
        /// </summary>
        public enum Filters
        {
            AttachmentFilter = 0,
            BlockedMailFilter,
            BlockedIpListFilter,
            BlockedKeywordFilter,
            ClamWinFilter,
            NullSenderFilter,
            NullSubjectFilter,
            RblFilter,
            RulesFilter,
            SpamAssasinFilter,
        }
    }


}


